<?php

namespace app\admin\controller\yunfood\food;

use addons\yunfood\library\Super;
use addons\yunfood\model\Shop;
use app\admin\model\yunfood\FoodParam as FoodParamModel;
use addons\yunfood\library\Backend;

/**
 * 菜品参数
 */
class Param extends Backend
{
    /**
     * @var FoodParamModel
     */
    protected $model;

    protected $shopField = 'shop_ids';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new FoodParamModel();

        // 关联门店
        $this->view->assign('shopId', $this->shopId);
        $this->assignconfig('shopId', $this->shopId);

        // 门店
        $shopList = Shop::getOptionList($this->getShopWhere(null, 'id'), true, false);
        $this->view->assign('shopList', $shopList);
        $this->assignconfig('shopList', $shopList);

        // 类型
        $this->view->assign('typeList', $this->model::getTypeList());
        $this->assignconfig('typeList', $this->model::getTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $type = $this->request->get('type');
        if ($this->request->isAjax()) {
            // 转发到selectParam
            if ($keyField = $this->request->request('keyField')) {
                $where = null;
                if ($keyValue = $this->request->request('keyValue')) {
                    $where = function ($query) use ($keyField, $keyValue) {
                        $query->where($keyField, 'in', explode(',', $keyValue));
                    };
                }
                if ($type) {
                    $total = $this->model->where('type', $type)->where($where)->count();
                    $list = $this->model->where('type', $type)->where($where)->select();
                } else {
                    $total = $this->model->where($where)->count();
                    $list = $this->model->where($where)->select();
                }
                $list = Super::arrayGetSet($list, [
                    'id',
                    'name' => function ($item) {
                        return $item->name . ($item->note ? '(' . $item->note . ')' : '');
                    },
                    'pid'  => function ($item) {
                        return 0;
                    }
                ], true);

                return json(['list' => $list, 'total' => $total]);
            }

            // 重载查询条件
            $filter = $this->request->get('filter');
            $op = $this->request->get('op');
            list($filter, $op) = $this->formatFilterOp($filter, $op);
            $this->request->get(['filter' => $filter, 'op' => $op]);

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 查询门店
            $where = $this->getShopWhere($where, 'shop_ids');
            $query = $this->model->where($where);
            if ($type) {
                $query->where('type', $type);
            }
            $list = $query->order($sort, $order)->limit($offset, $limit)->paginate($limit);
            foreach ($list->items() as $item) {
                $item->append(['shop_text', 'items_text']);
                if (! $this->superAdmin) {
                    if (empty($item->shop_ids) || strpos($item->shop_ids, ',') !== false) {
                        $item['mute_operate'] = true;
                    }
                }
            }
            $result = array(
                'total' => $list->total(),
                'rows'  => $list->items(),
            );

            return json($result);
        }

        // 选择
        $choose = $this->request->get('choose');
        $this->view->assign('choose', $choose);
        $this->assignconfig('choose', $choose);

        return $this->view->fetch();
    }

    /**
     * 格式化查询条件
     *
     * @param $filter
     * @param $op
     * @return array
     */
    private function formatFilterOp($filter, $op)
    {
        $filter = json_decode($filter, true);
        $op = json_decode($op, true);
        if (array_key_exists('shopId', $filter)) {
            if ($filter['shopId'] == 0) {
                $filter['shop_ids'] = '';
                $op['shop_ids'] = '=';
            } else {
                $filter['shop_ids'] = $filter['shopId'] . '';
                $op['shop_ids'] = 'find_in_set';
            }
            unset($filter['shopId'], $op['shopId']);
        }

        return [json_encode($filter), json_encode($op)];
    }

    /**
     * 保存
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $foodParam = new FoodParamModel();
                $foodParam->shop_ids = $this->shopId ?: '';
                $foodParam['type'] = $params['type'];
                $foodParam['name'] = $params['name'];
                $foodParam->items = $params['items'];
                $foodParam->note = date('Y-m-d H:i 来自菜品');
                $foodParam->save();
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }


    public function recyclebin()
    {
        return;
    }

    public function destroy($ids = null)
    {
        return;
    }

    public function restore($ids = null)
    {
        return;
    }
}
